package com.qipay.sp.excutor.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AlipayWapTradeQueryExcutor extends AbstractExcutor {

    private final static String CONFIG_APPID_NAME = "appid";
    private final static String CONFIG_RSA_PUBLIC_ALIPAY_NAME = "rsa_public_key_alipay";
    private final static String CONFIG_RSA_PRIVATE_NAME = "rsa_private_key";
    private final static String API_PARAM_OUT_TRADE_NO = "out_trade_no";
    private final static String API_PARAM_TRADE_NO = "trade_no";
    private final static String API_URL = "https://openapi.alipay.com/gateway.do";

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.ALIPAY_WAP;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(AlipayWapTradeQueryExcutor.API_PARAM_OUT_TRADE_NO, order.getTradeNo());
        apiParams.put(AlipayWapTradeQueryExcutor.API_PARAM_TRADE_NO, order.getSpTradeNo());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {

        Object appId = getVal(spconfig, AlipayWapTradeQueryExcutor.CONFIG_APPID_NAME);
        Object rsaPrivateKey = getVal(spconfig, AlipayWapTradeQueryExcutor.CONFIG_RSA_PRIVATE_NAME);
        Object rsaPublicKeyAlipay = getVal(spconfig, AlipayWapTradeQueryExcutor.CONFIG_RSA_PUBLIC_ALIPAY_NAME);
        Object outTradeNo = getVal(params, AlipayWapTradeQueryExcutor.API_PARAM_OUT_TRADE_NO);
        Object tradeNo = "";


        AlipayClient alipayClient = new DefaultAlipayClient(API_URL, appId.toString(), rsaPrivateKey.toString(), "json", "UTF-8", rsaPublicKeyAlipay.toString(), "RSA2"); // 获得初始化的AlipayClient
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\""+ outTradeNo +"\"," +
                "\"trade_no\":\""+ tradeNo +"\"" +
                "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result_code", "0");
        resultMap.put("trade_state", "10000".equals(response.getCode())? "SUCCESS":"NOTPAY");
        resultMap.put("trade_no", response.getOutTradeNo());
        resultMap.put("out_transaction_id", response.getTradeNo());

        return resultMap;
    }
}
